package com.e3roid.examples;

import java.util.ArrayList;

import android.view.MotionEvent;
import android.widget.Toast;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.sprite.AnimatedSprite;
import com.e3roid.drawable.texture.TiledTexture;

public class AnimatedSpriteExample extends E3Activity {

	private final static int WIDTH  = 320;
	private final static int HEIGHT = 480;
	
	private TiledTexture texture;
	private AnimatedSprite sprite;

	@Override
	public E3Engine onLoadEngine() {
		E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);
		engine.requestFullScreen();
		engine.requestPortrait();
		return engine;
	}

	@Override
	public E3Scene onLoadScene() {
		E3Scene scene = new E3Scene();
		scene.addEventListener(this);
		
		int centerX = (getWidth()  - texture.getTileWidth())  / 2;
		int centerY = (getHeight() - texture.getTileHeight()) / 2;
		
		// Add animation frames from tile.
		ArrayList<AnimatedSprite.Frame> frames = new ArrayList<AnimatedSprite.Frame>();
		frames.add(new AnimatedSprite.Frame(0, 0));
		frames.add(new AnimatedSprite.Frame(1, 0));
		frames.add(new AnimatedSprite.Frame(2, 0));
		frames.add(new AnimatedSprite.Frame(3, 0));
		
		// Start animation with 500msec, infinite loop.
		sprite = new AnimatedSprite(texture, centerX, centerY);
		sprite.animate(500, frames);
		
		scene.getTopLayer().add(sprite);
		scene.setBackgroundColor(0.94f, 1.00f, 0.94f, 1);
		Toast.makeText(this, "Touch screen to move the sprite.", Toast.LENGTH_LONG).show();
		return scene;
	}

	@Override
	public void onLoadResources() {
		// 31x49 pixel sprite with 1px border and (0,0) tile.
		texture = new TiledTexture("king.png", 31, 49, 0, 0, 3, 2, this);
	}

	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
		if (sprite != null) {
			if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
				// x and y must be adjusted to scene's screen position by scene.getSceneEventX,Y
				// because MotionEvent's getX() and getY() returns pixel position of the actual device.
				int x = getTouchEventX(scene, motionEvent) - (texture.getTileWidth()  / 2);
				int y = getTouchEventY(scene, motionEvent) - (texture.getTileHeight() / 2);
				sprite.move(x, y);
				
				// In order to stop the animation, just call stop() method like below.
				// if (sprite.isAnimated()) sprite.stop();
			}
		}
		return false;
	}

}
